﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Serialization;
using System.Text;
using System.Threading.Tasks;

namespace G.Log
{
    /// <summary>
    /// 日志数据结构
    /// </summary>
    [DataContract]
    public class LogData
    {
        /// <summary>
        /// 产生错误的日期
        /// </summary>
        [DataMember]
        public DateTime Date { get; set; }
        /// <summary>
        /// 错误标题
        /// </summary>
        [DataMember]
        public string Title { get; set; }
        /// <summary>
        /// 错误消息
        /// </summary>
        [DataMember]
        public string Message { get; set; }
        /// <summary>
        /// 错误等级
        /// </summary>
        [DataMember]
        public int ErorrLevel { get; set; }

        public LogData(string title, string message, int erorrLevel = 1)
        {
            this.Date = DateTime.Now;;
            this.Title = title;
            this.Message = message;
            this.ErorrLevel = erorrLevel;
        }
    }



    public static class LogService
    {
        private static LogDataBase DB;
        public static async void Save(LogData logData)
        {
            if (DB == null)
            {
                DB = new LogDataBase();
                await DB.InitialBatabaseAsync();
            }
            DB.LogTable.Add(logData);
            await DB.SubmitChanges();
        }

        public static async Task<LogData[]> ReadLogData()
        {
            if (DB == null)
            {
                DB = new LogDataBase();
                await DB.InitialBatabaseAsync();
            }
            return DB.LogTable.ToArray();
        }

        public static async void Clear()
        {
            if (DB == null)
            {
                DB = new LogDataBase();
                await DB.InitialBatabaseAsync();
            }
            DB.LogTable.Clear();
            await DB.SubmitChanges();
        }
    }
}
